/* PhotoFlow - animated image viewer for mobile devices
 *
 * Copyright (C) 2008 Ariya Hidayat (ariya.hidayat@gmail.com)
 * Copyright (C) 2007 Ariya Hidayat (ariya.hidayat@gmail.com)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this library; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA
 *
 */

#include "PhotoBrowser.h"

#include "ImageLoader.h"
#include "pictureflow.h"

#if defined(PHOTOFLOW_QT4)
#include <QDir>
#include <QImage>
#include <QImageReader>
#include <QTimer>
#endif

#if defined(PHOTOFLOW_QT3) || defined(PHOTOFLOW_QT2)
#include <qdir.h>
#include <qimage.h>
#include <qtimer.h>
#endif

#if defined(PHOTOFLOW_NOTHREAD)
#define ImageLoader PlainImageLoader
#endif

class PhotoBrowser::Private
{
public:
  QString imagePath;
  QStringList imageFiles;
  QTimer* updateTimer;
  ImageLoader* worker;
};

PhotoBrowser::PhotoBrowser(QWidget* parent): PictureFlow(parent)
{
  d = new Private;

  d->updateTimer = new QTimer;
  connect(d->updateTimer, SIGNAL(timeout()), this, SLOT(updateImageData()));

  d->worker = new ImageLoader;

  connect(this, SIGNAL(centerIndexChanged(int)), this, SLOT(preload()));
  setBackgroundColor(Qt::white);
}

PhotoBrowser::~PhotoBrowser()
{
  delete d->worker;
  delete d->updateTimer;
  delete d;
}

QString PhotoBrowser::imagePath() const
{
  return d->imagePath;
}

// get list of all files in a directory (will be filtered later)
// this is usually very fast so no need to put it in a separate thread
#if defined(PHOTOFLOW_QT4)
static QStringList findFiles(const QString& path = QString())
{
  QStringList files;

  QDir dir = QDir::current();
  if(!path.isEmpty())
    dir = QDir(path);

  dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
  QFileInfoList list = dir.entryInfoList();
  for (int i = 0; i < list.size(); ++i) 
  {
    QFileInfo fileInfo = list.at(i);
    files.append(dir.absoluteFilePath(fileInfo.fileName()));
  }

  return files;
}
#endif
#if defined(PHOTOFLOW_QT3) || defined(PHOTOFLOW_QT2)
static QStringList findFiles(const QString& path = QString())
{
  QStringList files;

  QDir dir = QDir::current();
  if(!path.isEmpty())
    dir = QDir(path);

  dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
  const QFileInfoList* list = dir.entryInfoList();
  if(list) 
  {
    QFileInfoListIterator it( *list );
    QFileInfo * fi;
    while( (fi=it.current()) != 0 ) 
    {
      ++it;
      files.append(dir.absFilePath(fi->fileName()));
    }
  }

  return files;
}
#endif

// take only files which are readable (as images)
// also seems to be fast as it does a quick check only
#if defined(PHOTOFLOW_QT4)
static QStringList filterImages(const QStringList& files)
{
  QStringList imageFiles;

  QImageReader reader;
  foreach(QString fname, files)
  {
    reader.setFileName(fname);
    if(reader.canRead())
      imageFiles += fname;
  }

  return imageFiles;
}
#endif
#if defined(PHOTOFLOW_QT3) || defined(PHOTOFLOW_QT2)
// FIXME
static QStringList filterImages(const QStringList& files)
{
  return files;
}
#endif

void PhotoBrowser::setImagePath(const QString& path)
{
  clear();

  d->imagePath = path;
  d->imageFiles = filterImages(findFiles(path));

  // populate with empty images
  for(int i = 0; i < (int)d->imageFiles.count(); i++)
    addSlide(QImage());

  setCenterIndex(0);
  preload();
}

void PhotoBrowser::preload()
{
  d->updateTimer->start(100);
}

void PhotoBrowser::updateImageData()
{
  // can't do anything, wait for the next possibility
  if(d->worker->busy())
    return;

  // set image of last one
  if(d->worker->index() >= 0)
    setSlide(d->worker->index(), d->worker->result()); 

  // try to load only few images on the left and right side 
  // i.e. all visible ones plus some extra
#define COUNT 10  
  int indexes[2*COUNT+1];
  int center = centerIndex();
  indexes[0] = center;
  for(int j = 0; j < COUNT; j++)
  {
    indexes[j*2+1] = center+j+1;
    indexes[j*2+2] = center-j-1;
  }  

  for(int c = 0; c < 2*COUNT+1; c++)
  {
    int i = indexes[c];
    if((i >= 0) && (i < slideCount()))
    if(slide(i).isNull())
    {
      // schedule thumbnail generation
      QString fname = d->imageFiles[i];
      d->worker->generate(i, fname, slideSize());
      return;
    }
  }

  // no need to generate anything? stop polling...
  d->updateTimer->stop();
}
